package com.example.demo33.service;

import com.example.demo33.entity.InviteCode;
import com.example.demo33.mode.InviteCodeRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Random;

@Service
public class InviteCodeService {
    private static final String SECRET_PASSWORD = "wenwen123";
    private static final String CHARACTERS = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ"; // 34个字符（去除了易混淆字符）
    private static final int CODE_LENGTH = 8;
    private static final int MAX_ATTEMPTS = 10;

    private final InviteCodeRepository inviteCodeRepository;

    public InviteCodeService(InviteCodeRepository inviteCodeRepository) {
        this.inviteCodeRepository = inviteCodeRepository;
    }

    @Transactional
    public InviteCode generateInviteCode(String password, Long creatorId) {
        // 1. 验证口令
        if (!SECRET_PASSWORD.equals(password)) {
            throw new SecurityException("口令验证失败");
        }

        // 2. 生成唯一邀请码
        String code;
        boolean isUnique;
        int attempts = 0;
        Random random = new Random();

        do {
            // 生成随机码
            StringBuilder sb = new StringBuilder(CODE_LENGTH);
            for (int i = 0; i < CODE_LENGTH; i++) {
                sb.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
            }
            code = sb.toString();

            // 检查唯一性
            isUnique = !inviteCodeRepository.existsByCode(code);
            attempts++;
        } while (!isUnique && attempts < MAX_ATTEMPTS);

        // 3. 备选方案（冲突时）
        if (!isUnique) {
            code = "U" + String.format("%07d", creatorId % 10000000);
            if (inviteCodeRepository.existsByCode(code)) {
                code += CHARACTERS.charAt(random.nextInt(CHARACTERS.length()));
            }
        }

        // 4. 保存到数据库
        InviteCode inviteCode = new InviteCode();
        inviteCode.setCode(code);
        inviteCode.setCreatorId(creatorId);
        inviteCode.setUsed(false);
        return inviteCodeRepository.save(inviteCode);
    }
}